import 'package:card_topia/common_provider/page_provider.dart';
import 'package:card_topia/common_provider/user_provider.dart';
import 'package:card_topia/design_specifications.dart';
import 'package:card_topia/my_router.dart';
import 'package:card_topia/pages/center_page/center_page.dart';
import 'package:card_topia/pages/login_page/login_page.dart';
import 'package:card_topia/utils/event_util.dart';
import 'package:ficonsax/ficonsax.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

///自定义底部导航栏

class MyBottomNavigationBar extends ConsumerStatefulWidget {
  const MyBottomNavigationBar({
    super.key,
  });

  @override
  ConsumerState<MyBottomNavigationBar> createState() =>
      _MyBottomNavigationBarState();
}

class _MyBottomNavigationBarState extends ConsumerState<MyBottomNavigationBar> {
  late final user = ref.watch(userInfoProvider);
  late final pagePod = ref.read(pageProvider);
  final List<Map<String, dynamic>> _items = [
    {
      "label": "首页",
      "icon": IconsaxOutline.grammerly,
      "activeIcon": IconsaxBold.grammerly
    },
    {
      "label": "集市",
      "icon": IconsaxOutline.shopping_cart,
      "activeIcon": IconsaxBold.shopping_cart
    },
    {},
    {
      "label": "消息",
      "icon": IconsaxOutline.message,
      "activeIcon": IconsaxBold.message
    },
    {
      "label": "我的",
      "icon": IconsaxOutline.user_tag,
      "activeIcon": IconsaxBold.user_tag
    },
  ];

  onTap(int index) async {
    pagePod.setAim(index);
    if (index == 2) {
      // showCupertinoDialog(
      //     context: context,
      //     // shape:
      //     //     RoundedRectangleBorder(borderRadius: BorderRadius.circular(20.w)),
      //     // backgroundColor: scaffoldBackgroundColor,
      //   // showDragHandle: true
      //
      //   builder: (_) => CenterPage(),
      // );
      showModalBottomSheet(
          context: context,
          backgroundColor: Colors.transparent,
          barrierColor: textColor.withOpacity(0.5),
          builder: (_) => Container(
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.circular(20.w)
            ),
            child: SingleChildScrollView(
                    child: Column(
                  children: [
                    SizedBox(height: 32.w,),
                    CenterPageItem(type: 2),
                    CenterPageItem(type: 1),
                    CenterPageItem(type: 0),
                    SizedBox(height: 32.w,),
                    CenterPageBtn(),
                    SizedBox(height: 45.w,)
                  ],
                )),
          ));
    } else if (index == 4 || index == 3) {
      if (user.userInfo == null) {
        // context.push(MyRouter.loginPage);
        MyRouter.push(page: const LoginPage());
      } else {
        pagePod.changeTab(index);
      }
    } else {
      pagePod.changeTab(index);
    }
  }

  @override
  void initState() {
    super.initState();
    listenTab();
  }

  //监听tab
  listenTab() {
    EventUtil.eventBus.on<TabChangeEvent>().listen((event) {
      pagePod.changeTab(event.index);
    });
  }

  @override
  Widget build(BuildContext context) {
    return SingleChildScrollView(
      child: Container(
        decoration: BoxDecoration(
            // color: Colors.white,
            borderRadius: BorderRadius.circular(8.w)),
        margin: EdgeInsets.only(
            // left: 16.w,
            // right: 16.w,
            bottom: MediaQuery.of(context).padding.bottom),
        padding: EdgeInsets.symmetric(vertical: 8.w),
        child: Row(
          children: _items.map((e) {
            return e.isEmpty
                ? AnimatedScaleButton(
                    onTap: () => onTap(_items.indexOf(e)),
                    child: Hero(
                        tag: "center_btn",
                        child: const Icon(
                          Icons.add_rounded,
                          color: Colors.white,
                        )),
                  )
                : Expanded(
                    child: AnimatedNavigationBarItem(
                        onTap: (index) {
                          onTap(_items.indexOf(e));
                        },
                        currentIndex: ref.watch(pageProvider).currentPage,
                        index: _items.indexOf(e),
                        data: e),
                  );
          }).toList(),
        ),
      ),
    );
  }
}

///自定义缩放底部按钮
class AnimatedNavigationBarItem extends StatefulWidget {
  const AnimatedNavigationBarItem(
      {super.key,
      required this.data,
      required this.currentIndex,
      required this.index,
      required this.onTap});

  final Map<String, dynamic> data;
  final int currentIndex;
  final int index;
  final Function(int) onTap;

  @override
  State<AnimatedNavigationBarItem> createState() =>
      _AnimatedNavigationBarItemState();
}

class _AnimatedNavigationBarItemState extends State<AnimatedNavigationBarItem> {
  bool _isScale = false;

  @override
  Widget build(BuildContext context) {
    return InkWell(
      onTapDown: (_) {
        _isScale = true;
        setState(() {});
      },
      onTapCancel: () {
        _isScale = false;
        setState(() {});
      },
      onTapUp: (_) {
        _isScale = false;
        setState(() {});
        widget.onTap(widget.index);
      },
      child: Column(
        children: [
          AnimatedScale(
            duration: const Duration(milliseconds: 100),
            scale: _isScale ? 0.7 : 1,
            curve: Curves.easeInOut,
            child: Icon(
              widget.currentIndex == widget.index
                  ? widget.data['activeIcon']
                  : widget.data['icon'],
              color: widget.currentIndex == widget.index
                  ? themeColor
                  : unSelectColor,
            ),
          ),
          SizedBox(
            height: 4.sp,
          ),
          Text(
            "${widget.data['label']}",
            style: TextStyle(
                fontSize: 12.sp,
                color: widget.currentIndex == widget.index
                    ? themeColor
                    : unSelectColor),
          )
        ],
      ),
    );
  }
}

///自定义缩放按钮
class AnimatedScaleButton extends StatefulWidget {
  const AnimatedScaleButton(
      {super.key, required this.onTap, required this.child});

  final Function onTap;
  final Widget child;

  @override
  State<AnimatedScaleButton> createState() => _AnimatedScaleButtonState();
}

class _AnimatedScaleButtonState extends State<AnimatedScaleButton> {
  bool _isScale = false;

  @override
  Widget build(BuildContext context) {
    return InkWell(
      onTapDown: (_) {
        setState(() {
          _isScale = true;
        });
      },
      onTapCancel: () {
        setState(() {
          _isScale = false;
        });
      },
      onTapUp: (_) {
        setState(() {
          _isScale = false;
        });
        widget.onTap();
      },
      child: AnimatedScale(
        duration: const Duration(milliseconds: 100),
        curve: Curves.easeInOut,
        scale: _isScale ? 0.8 : 1,
        child: Container(
          margin: EdgeInsets.symmetric(horizontal: 20.w),
          padding: EdgeInsets.all(8.w),
          decoration: BoxDecoration(
              color: themeColor, borderRadius: BorderRadius.circular(16.w)),
          child: widget.child,
        ),
      ),
    );
  }
}
